package com.song.druid.config.web;


import com.song.druid.constant.DatePatternConstant;
import com.song.druid.constant.DateRegex;
import com.song.druid.util.LocalDateTimeUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    @Override
    public LocalDateTime convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if (source.matches(DateRegex.YEAR + "-" + DateRegex.MONTH + "-" + DateRegex.DAY + " " + DateRegex.HOUR + ":" + DateRegex.MINUTE + ":" + DateRegex.SECOND)){
            return LocalDateTimeUtil.stringToLocalDateTime(source, DatePatternConstant.DEFAULT_PATTERN);
        }else if (source.matches(DateRegex.YEAR + "/" + DateRegex.MONTH + "/" + DateRegex.DAY + " " + DateRegex.HOUR + ":" + DateRegex.MINUTE + ":" + DateRegex.SECOND)){
            return LocalDateTimeUtil.stringToLocalDateTime(source, DatePatternConstant.PATTERN);
        }else if (source.matches(DateRegex.YEAR + "." + DateRegex.MONTH + "." + DateRegex.DAY + " " + DateRegex.HOUR + ":" + DateRegex.MINUTE + ":" + DateRegex.SECOND)){
            return LocalDateTimeUtil.stringToLocalDateTime(source, DatePatternConstant.POINT_PATTERN);
        }else {
            throw new IllegalArgumentException("Invalid date value '" + source + "'");
        }
    }
}
